package com.giteeoauth.controller;

import cn.hutool.json.JSONObject;
import com.giteeoauth.util.GiteeHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.UUID;

/**
 * @description:
 * @Author 兔子不吃窝边曹
 * @create 2022/7/28 9:27
 **/
@Controller
public class GiteeController {

    @Value("${gitee.oauth.client_id}")
    public String CLIENT_ID;

    @Value("${gitee.oauth.client_secret}")
    public String CLIENT_SECRET;

    @Value("${gitee.oauth.callback}")
    public String CALLBACK_URL;

    /**
     * 请求授权页面
     */
    @GetMapping(value = "/auth")
    public String giteeAuth(HttpSession session) {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1：获取Authorization Code
        String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&client_id=" + CLIENT_ID +
                "&redirect_uri=" + URLEncoder.encode(CALLBACK_URL) +
                "&state=" + uuid +
                "&scope=user_info";
        // 因为使用的是thymeleaf模板引擎，所以是无法解析一个网址的，只能重定向
        System.out.println(url);
        return "redirect:" + url;
    }

    /**
     * 授权回调
     */
    @GetMapping(value = "/authredirect")
    public String giteeCallback(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        // 验证信息我们发送的状态码
        if (Objects.isNull(state) || Objects.isNull(uuid)) {
            return "index";
        }

        // 状态码不正确，直接返回登录页面
        if (!uuid.equals(state)) {
            return "index";
        }

        // Step2：通过Authorization Code获取Access Token
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&client_id=" + CLIENT_ID +
                "&client_secret=" + CLIENT_SECRET +
                "&code=" + code +
                "&redirect_uri=" + CALLBACK_URL;
        String accessToken = GiteeHttpClient.getAccessToken(url);

        // Step3: 获取用户信息
        url = "https://gitee.com/api/v5/user?access_token=" + accessToken;
        JSONObject jsonObject = GiteeHttpClient.getUserInfo(url);
        // 获取到用户信息之后，就该写你自己的业务逻辑了
        System.out.println(jsonObject);
        return "hello";
    }
}

